package com.dries.portal.module.portal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dries.common.api.CommonResult;
import com.dries.portal.module.portal.entity.Discuss;
import com.dries.portal.module.portal.entity.DiscussDetail;
import com.dries.portal.module.portal.form.AddDiscussDetailForm;
import com.dries.portal.module.portal.mapper.DiscussMapper;
import com.dries.portal.module.portal.service.IDiscussDetailService;
import com.dries.portal.module.portal.service.IDiscussService;
import com.dries.portal.module.portal.vo.DiscussVo;
import com.dries.portal.module.user.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DiscussServiceImpl extends ServiceImpl<DiscussMapper, Discuss> implements IDiscussService {

    @Resource
    private UserService userService;
    @Resource
    private IDiscussDetailService discussDetailService;

    /**
     * 查询用户评价列表
     */
    @Override
    public PageInfo<DiscussVo> listByDiscussVo(Integer pageNumber, Integer pageSize) {

        PageHelper.startPage(pageNumber,pageSize);
        List<Discuss> discusses = baseMapper.selectList(null);
        List<DiscussVo> discussVos = discusses.stream().map(this::buildDiscussVo).collect(Collectors.toList());

        return new PageInfo<>(discussVos);
    }

    /**
     * 保存用户评价
     * @param form
     */
    @Transactional
    @Override
    public CommonResult saveByAddDiscussDetailForm(AddDiscussDetailForm form) {

        // UserEntity user = userService.getCurrentUser().getData();

        // 1.保存Discuss内容
        Discuss discuss = new Discuss();
        BeanUtils.copyProperties(form, discuss);
        discuss.setUserId(form.getUserId());
        discuss.setUserAvatar(form.getUserAvatar());
        discuss.setUserNickname(form.getUserNickname());

        boolean a = save(discuss);

        // 2.保存Discuss_Detail 内容
        DiscussDetail discussDetail = new DiscussDetail();
        BeanUtils.copyProperties(form, discussDetail);
        discussDetail.setDiscussId(discuss.getId());
        discussDetail.setDiscussImgs(
                form.getDiscussImgs().stream()
                .map(String::toString).collect(Collectors.joining(","))
        );
        boolean b = discussDetailService.save(discussDetail);

        if ( a && b) {
            return CommonResult.success("评价成功！");
        } else return CommonResult.failed();

    }

    /**
     * 构造返回前端用户评价的VO对象
     * @return
     */
    private DiscussVo buildDiscussVo(Discuss discuss){
        DiscussVo discussVo = new DiscussVo();
        BeanUtils.copyProperties(discuss, discussVo);
        return discussVo;
    }
}